import { useEffect, useState } from 'react';
import { Breadcrumb, Layout, Menu, theme } from 'antd';
import { children } from '../../router';
import { Outlet, useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import type { RootState } from '../../store';
import style from './style.module.scss';
import { Avatar } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import Logo from '../../compages/Logo';

const { Header, Content, Footer, Sider } = Layout;

function Index() {
    // 使用useSearchParams获取查询参数
    const [mb] = useSearchParams()
    console.log('mb', mb)
    // 从localStorage中获取pic、token、name
    const pic = localStorage.getItem('pic')
    const token = localStorage.getItem('token')
    const name = localStorage.getItem('name')
    // 使用useNavigate进行页面跳转
    const nav = useNavigate()
    // 使用useLocation获取当前路径
    const { pathname } = useLocation()
    // 使用useSelector获取主题模式
    const themeMode = useSelector((state: RootState) => state.theme.mode);

    // 路由递归
    const { t } = useTranslation();

    // 定义原始菜单项类型
    type RawMenuItem = { path: string; key: string; children?: RawMenuItem[] };
    // 定义菜单项类型
    type MenuItem = {
      key: string;
      icon: string;
      children: MenuItem[] | null;
      label: string;
    };
    // 递归处理菜单项
    const ly = (arr: RawMenuItem[]): MenuItem[] => {
      return arr.map((i) => ({
                key: i.path === '/home/number' ? '/number' : i.path,
                icon: '',
                children: i.children ? ly(i.children) : null,
        label: t(`menu.${i.key}`),
      }));
    };
    // 获取菜单项
    const items = ly(children)
    // 定义菜单折叠状态
    const [collapsed, setCollapsed] = useState(false);
    // 获取主题颜色和圆角
    const {
        token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();

    // 清除token，跳转到登录页
    const login = () => {
        localStorage.clear()
        nav('/login')
    }

    // 菜单点击处理
    const handleMenuClick = ({ key }: { key: string }) => {
        nav(key)
    }

    // 动态国际化面包屑
    const pathSnippets = pathname.split('/').filter(i => i);
    const breadcrumbItems = [
        {
            key: 'home',
            title: t('breadcrumb.home'),
            path: '/home',
        },
        ...pathSnippets.map((snippet, idx) => {
            const url = `/${pathSnippets.slice(0, idx + 1).join('/')}`;
            return {
                key: snippet,
                title: t(`breadcrumb.${snippet}`),
                path: url,
            };
        }),
    ];

    // 监听主题模式变化，设置页面主题
    useEffect(() => {
        document.body.setAttribute('data-theme', themeMode);
    }, [themeMode]);

    // 定义显示状态
    const [show, setShow] = useState(false)
    const [show2, setShow2] = useState(1)
    // 监听show2变化，切换显示状态
    useEffect(() => {
        console.log('show2', show2);
        if(show2%2==0){
            setShow(true)
        }else{
            setShow(false)
        }
    }, [show2])
    const xz = () => {
        setShow2(show2+1)
    }

    return (
        // 菜单栏
        <Layout style={{ minHeight: '100vh' }} >
            <Sider collapsible collapsed={collapsed} onCollapse={(value: boolean) => setCollapsed(value)} style={{ background: '#001529' }}>
                <div className="demo-logo-vertical" />
                <Menu
                    theme="dark"
                    style={{ background: '#001529', color: '#fff' }}
                    defaultSelectedKeys={[pathname]}
                    selectedKeys={[pathname]}
                    mode="inline"
                    items={items}
                    onClick={handleMenuClick}
                />
            </Sider>
            <Layout>
                
                <Header style={{ padding: 0, background: colorBgContainer, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    {/* logo */}
                    <div className={style.logo}>
                        <Logo size="large" animated={true} />
                    </div>
                    {/* 头像 */}
                    {token ? <div className={style.tx}>
                        <Avatar size={48} src={pic} />
                        <span onClick={xz}>{name === 'admin' ? t('home.admin', { name }) : t('home.user', { name })}</span>
                    </div> : <div className={style.tx}>
                        <Avatar size={48} icon={<UserOutlined />} />
                        <span onClick={xz}>{name === 'admin' ? t('home.admin', { name }) : t('home.user', { name })}</span>
                    </div>
                    }
                    {show===true? <div className={style.xz}>
                       <div>
                    {/* 点击跳转登录页 */}
                        <button onClick={login}>{t('home.login')}</button>
                    </div>
                    </div>:null}
                </Header>
                <Content style={{ margin: '0 16px' }}>
                    {/* 优化后的国际化面包屑 */}
                    <Breadcrumb style={{ margin: '16px 0' }}>
                        {breadcrumbItems.map(item => (
                            <Breadcrumb.Item key={item.key}>{item.title}</Breadcrumb.Item>
                        ))}
                    </Breadcrumb>
                    <div
                        style={{
                            padding: 24,
                            minHeight: 360,
                            borderRadius: borderRadiusLG,
                        }}
                        className={style.box}
                    >
                        <Outlet></Outlet>
                    </div>
                </Content>
                <Footer style={{ textAlign: 'center' }}>
                    用户管理系统
                </Footer>
            </Layout>
        </Layout>
    )
}

export default Index
